# backend/services/isbn_service.py
from fastapi import HTTPException
from backend.utils.api_client import fetch_book_info
from backend.crud.book_crud import create_book


async def add_book_by_isbn(db, isbn: str, library_id: int, user_id: int):
    # 尝试从API获取图书信息
    book_info = await fetch_book_info(isbn)

    if not book_info:
        raise HTTPException(
            status_code=404,
            detail="无法通过ISBN找到图书信息，请手动添加"
        )

    # 创建图书记录
    return create_book(
        db=db,
        isbn=isbn,
        title=book_info["title"],
        author=book_info["author"],
        cover_url=book_info.get("cover_url", ""),
        library_id=library_id,
        added_by=user_id
    )
